'''
ComPort : Python Arduino API : ComPort Module
author:     Steve De Jongh ( dejongh[dot]st[at]gmail[dot]com )
Licence type: MIT


Copyright (c) 2013 Steve De Jongh (dejongh[dot]st[at]gmail[dot]com)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
'''

import serial
import threading

class ComPort(threading.Thread):
    """
    Usage: myComPort = ComPort(comport,speed)
    Creates an object to manage a serial connection
    """
    def __init__(self,comport,speed,callback):
        threading.Thread.__init__(self)
        self._comport = comport
        self._speed = speed
        self._active = False
        self._connection = None
        self._callback = callback
        self._initiated = False

    def run(self):
        """
        ComPort thread main routine
        """
        if self._connection is None:
            self.launch()
        dataBytes = ''
        while ( self._active ):
            if not self._initiated:
                inByte = self._connection.read()
                if inByte == 'A':
                    self.write('A')
                    self._initiated = True
                else:
                    self._connection.flushInput()
            else:
                try:
                    inByte = self._connection.read()
                    if inByte == chr(13):
                        self._callback(dataBytes.strip())
                        dataBytes = ''
                    else:
                        dataBytes = dataBytes + inByte
                except:
                    pass
                    

    def launch(self):
        """
        Usage: myComPort.launch()
        Starts the serial connection
        """
        self._connection = serial.Serial(self._comport,self._speed)
        self._active = True

    def terminate(self):
        """
        Usage: myComPort.terminate()
        Closes the serial connection and tries to make the thread decay
        """
        if self._connection is not None:
            self._connection.close()
            self._connection = None
            self._active = False

    def write(self,data):
        """
        Usage: myComPort.write(data)
        Sends data across the serial communication.
        Note: data must be a string
        """
        if self._active:
            self._connection.write(data)
        
# TEST CODE
if __name__ == '__main__':
    import time
    def callback(data):
        print data
    c = ComPort('COM4',115200,callback)
    c.start()
    time.sleep(10)
    c.terminate()
    
